<?php

namespace services\patient;

use common\components\Service;
use common\helpers\CommonHelper;
use common\models\base\Drug;
use common\models\base\DrugConfig;
use common\models\patient\DrugRecord;
use common\models\patient\DrugSurplus;
use common\models\patient\User;
use services\base\DrugConfigService;
use services\base\DrugService;
use services\clinic\ClinicService;
use services\clinic\TreatmentRoomService;
use Yii;

/**
 * Class DrugSurplusService
 * @package services\patient
 */
class DrugSurplusService extends Service
{
    /**
     * 患者药品列表
     * @param int $id
     * @return array
     */
    public function getPatientDrugList(int $id): array
    {
        $data = DrugSurplus::find()->alias('ds')
            ->select([
                'ds.id', 'ds.surplus_num', 'ds.drug_config_id', 'ds.patient_user_id',
                'dc.drug_id', 'dc.drug_type', 'dc.drug_volume', 'dc.water_type', 'dc.water_volume',
                'd.drug_name', 'd.drug_unit',
            ])
            ->innerJoin(DrugConfig::tableName().' dc', 'dc.id = ds.drug_config_id')
            ->leftJoin(Drug::tableName().' d', 'd.id = dc.drug_id')
            ->where([
                'ds.patient_user_id' => $id,
                'ds.status' => DrugSurplus::STATUS_ENABLE,
            ])
            ->orderBy([
                'ds.updated_at' => SORT_DESC,
                'ds.id' => SORT_DESC,
            ])
            ->asArray()
            ->all();

        return $this->getPatientDrugListFormat($data);
    }

    /**
     * 格式化
     * @param array $data
     * @return array
     */
    public function getPatientDrugListFormat(array $data): array
    {
        $jdList = $jzList = [];
        foreach ($data as $row) {
            $drugContent = DrugService::getDrugContent($row['drug_id'], $row['drug_name'], $row['drug_unit'], $row['drug_type'], $row['drug_volume'], $row['water_type'], $row['water_volume']);

            // 返回最后一次新增药品的备注
            $drugLastRecord = DrugRecord::find()
                ->select(['id', 'remark'])
                ->where(['drug_config_id' => $row['drug_config_id'], 'type' => DrugRecord::TYPE_ADD, 'patient_user_id' => $row['patient_user_id']])
                ->limit(1)->orderBy(['id' => SORT_DESC])
                ->asArray()->one();

            $item = [
                'id' => $row['id'],
                'surplus_num' => $row['surplus_num'],
//                'drug_config_id' => $row['drug_config_id'],
                'drug_content' => $drugContent,
                'drug_remark' => $drugLastRecord['remark'],
                'drug_config_id' => $row['drug_config_id'],
            ];

            if ($row['drug_type'] == DrugConfig::DRUG_TYPE_JD) {
                $jdList[] = $item;
            } else {
                $jzList[] = $item;
            }
        }

        return [
            'jd' => $jdList,
            'jz' => $jzList,
        ];
    }

    /**
     * 治疗报表左侧项目【治疗项目+输液药品】
     * @return array
     */
    public function getReportProjectList(): array
    {
        // 治疗项目列表
        $clinicProjectList = TreatmentRoomService::getRoomProjectList();
        // 药品配置列表
        $drugList = DrugService::getDrugAllList();
        // 获取筛选条件
        $userService = new UserService();
        $condition = $userService->getConditionList(['get_clinic' => 1], Yii::$app->params['project_id']);

        return [
            'clinic_project' => $clinicProjectList,
            'drug' => $drugList,
            'condition' => $condition,
        ];
    }

    /**
     * 治疗报表-输液药品患者统计
     * @param array $params
     * @param int $drugId
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getReportUserList(array $params, int $drugId, int $page, int $pageSize): array
    {
        $query = DrugSurplus::find()->alias('ds')
            ->select([
                'u.id', 'u.name', 'u.patient_card_id', 'u.age', 'u.gender', 'u.clinic_id',
                'SUM(ds.surplus_num) surplus_num'
            ])
            ->innerJoin(DrugConfig::tableName().' dc', 'dc.id = ds.drug_config_id')
            ->innerJoin(User::tableName().' u', 'u.id = ds.patient_user_id')
            ->where([
                'dc.drug_id' => $drugId,
                'ds.status' => DrugSurplus::STATUS_ENABLE,
                'u.project_id' => Yii::$app->params['project_id'],
                'u.status' => [User::STATUS_ENABLE, User::STATUS_INVALID]
            ])
            ->groupBy('u.id');
        if (isset($params['keywords']) && $params['keywords']) {
            $query->andWhere([
                'or',
                ['u.name' => $params['keywords']],
                ['u.patient_card_id' => $params['keywords']],
            ]);
        }
        if (isset($params['clinic_id']) && $params['clinic_id']) {
            $query->andWhere(['u.clinic_id' => $params['clinic_id']]);
        }
        if (isset($params['min_num']) && is_numeric($params['min_num'])) {
            $query->andWhere(['>=', 'surplus_num', $params['min_num']]);
        }
        if (isset($params['max_num']) && is_numeric($params['max_num'])) {
            $query->andWhere(['<=', 'surplus_num', $params['max_num']]);
        }
        $order = [
            'u.id' => SORT_ASC,
        ];
        $res = $this->getListPageRes($query, $page, $pageSize, $order);
        $res['list'] = $this->getReportUserListFormat($res['list'], $drugId);
        return $res;
    }

    /**
     * 格式化数据
     * @param array $data
     * @param int $drugId
     * @return array
     */
    public function getReportUserListFormat(array $data, int $drugId): array
    {
        $patientUserIds = array_column($data, 'id');
        // 患者购买+治疗数量
        $patientNumMap = DrugRecordService::getStatisticsList($patientUserIds, $drugId);
        // 诊室
        $clinicService = new ClinicService();
        $clinicMap = $clinicService->findList([
            'id' => array_column($data, 'clinic_id'),
            'indexBy' => 'id',
        ]);

        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'name' => $row['name'],
                'patient_card_id' => $row['patient_card_id'],
                'age' => $row['age'],
                'gender_str' => User::$genders[$row['gender']] ?? '',
                'clinic_name' => $clinicMap[$row['clinic_id']]['name'] ?? '',
                'buy_num' => $patientNumMap[$row['id']]['buy_num'] ?? 0,
                'treatment_num' => $patientNumMap[$row['id']]['treatment_num'] ?? 0,
                'surplus_num' => $row['surplus_num'],
            ];
        }
        return $list;
    }

    /**
     * 检测患者当天是否做过治疗
     * @param array $params
     * @return array|bool|mixed
     */
    public function checkTreatmentToday(array $params)
    {
        $drugLastRecord = DrugRecord::find()
            ->select(['id', 'remark'])
            ->where(['drug_config_id' => $params['drug_config_id'], 'type' => DrugRecord::TYPE_USE, 'patient_user_id' => $params['patient_user_id']])
            ->andWhere(['>=', 'created_at', strtotime(date('Y-m-d'))])
            ->limit(1)->orderBy(['id' => SORT_DESC])
            ->asArray()->one();
        if ($drugLastRecord) {// 存在则提示
            return false;
        }
        return true;
    }
}